//
//  WorkHomeVC.m
//  XLDoctor
//
//  Created by longma on 2018/7/27.
//  Copyright © 2018年 XLH. All rights reserved.
//

#import "MemberSelectAlertView.h"
#import "ArchivesSectionView.h"
#import "SelectMemberTbvCell.h"

static const CGFloat maxHeight = 550.0f;
static const CGFloat minHeight = 400.0f;

@interface MemberSelectAlertView ()<UITableViewDelegate,UITableViewDataSource,ArchivesSectionViewDelegate>

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *contentviewH;
@property (weak, nonatomic) IBOutlet UIView *contentview;
@property (weak, nonatomic) IBOutlet MJUIPickerItemAlertTopView *viewTop;

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *tempDataArray;
@property (nonatomic, strong) NSMutableArray *firstLetterArray;
@property (weak, nonatomic) IBOutlet UIView *viewContent;
@property (weak, nonatomic) IBOutlet MJUITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *letterBgView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *letterBgViewH;
@property (nonatomic, strong) ArchivesSectionView *letterView;
@property (weak, nonatomic) IBOutlet UIView *addMemberView;
@property (weak, nonatomic) IBOutlet UILabel *addMemberLabel;
@property (weak, nonatomic) IBOutlet UIImageView *addMemberImageView;
@end

@implementation MemberSelectAlertView
#pragma mark - 系统

- (void)viewDidLoad {
    [super viewDidLoad];

    self.contentviewH.constant = minHeight;
    self.baseAlertView.alertType = AlertTypeBottom;
    self.baseAlertView.contentHeight = minHeight;
    [self.baseAlertView initContentview:self.contentview];
    self.view.backgroundColor = UIColor.clearColor;
    
    if(self.isDetectionRecord){
        self.addMemberLabel.mj_localizable = @"All Members";
        self.addMemberImageView.image = MJUIImageMake(@"icon_shuanxing_g");
    }
 
    MJWeakSelf
    MJUITableView *tableView = self.tableView;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.estimatedSectionHeaderHeight = 0;
    tableView.estimatedSectionFooterHeight = 0;
    tableView.rowHeight = UITableViewAutomaticDimension;
    tableView.estimatedRowHeight = 50;
    tableView.backgroundColor = UIColor.clearColor;
    [tableView mj_cornerRadius:13];
    [SelectMemberTbvCell registerNibWithTableView:tableView];
    if(HealthHelper.shared.homePatientList.count){
        [self processData:HealthHelper.shared.homePatientList];
    }else{
        [self showEmptyView:self.tableView emptyStyle:EmptyViewSelectMember];
    }
    
    self.viewTop.contentView.backgroundColor = UIColor.mj_backgroundColor;
    self.viewTop.titleLabel.mj_localizable = @"Select Member";
    self.viewTop.titleLabelLeft.constant = 15;
    [self.viewTop.cancelButton mj_addAction:^(UIButton *button) {
        if(weakSelf.isGlobalDetection){
            [HealthHelper interruptionSaveAlertViewWithConfirmBlock:^{
                [weakSelf.baseAlertView dismiss];
            } cancelBlock:^{}];
        }else{
            [weakSelf.baseAlertView dismiss];
        }
    }];
    
    //
    ArchivesSectionView *letterView = [ArchivesSectionView mj_loadNibWithOwner:self];
    letterView.backgroundColor = UIColor.redColor;
    letterView.delegate = self;
    letterView.firstLetterArray = self.firstLetterArray;
    [self.letterBgView addSubview:letterView];
    [letterView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.letterBgView);
     }];
    self.letterView = letterView;
//    [self requestData];
    
    if(self.isGlobalDetection){
        self.addMemberView.hidden = true;
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

#pragma mark - 方法
- (IBAction)handleAddButtonClick:(UIButton *)sender {
    MJWeakSelf
    [self.baseAlertView dismissCompletion:^{
        if(weakSelf.handleAddMemberBlock){
            weakSelf.handleAddMemberBlock();
        }
    }];
}

- (void)requestData{
    
    MJWeakSelf
    [MJHttpNetWorking requestWithParams:@{} requestUri:patient_select requestType:RequestTypePost showLoading:false success:^(MJBaseModel *model) {
        
        if (model.code ==  200){
            NSArray *data = model.data;
            NSMutableArray *modelArray = [NSMutableArray array];//data.count
            for (int i = 0; i<data.count; i++) {
                PatientModel *rmodel = [PatientModel yy_modelWithDictionary:data[i]];
                [modelArray addObject:rmodel];
            }
            [weakSelf processData:modelArray];
         }
        
    } failure:^(NSError *error) {
        
    }];
}

- (void)processData:(NSArray *)modelArray{
    if(modelArray.count > 4){
        self.contentviewH.constant = maxHeight;
        self.baseAlertView.contentHeight = maxHeight;
    }
    if(modelArray.count){
        self.tableView.backgroundColor = UIColor.whiteColor;
    }
    
    [self.dataArray removeAllObjects];
    [self.dataArray addObjectsFromArray:modelArray];
    [self showEmptyView];
    
    //排序首字母
    [self sortAcronym];
    [self.tableView reloadData];
}

- (void)sortAcronym {
    if(self.dataArray.count){
        NSMutableArray *firstLetterArray = [NSMutableArray array];
        for (PatientModel *rmodel in self.dataArray) {
            //俄语排序
            if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleRU){
                NSString *firstLetter = rmodel.patientName.mj_firstRuLetter;
                if(![firstLetterArray containsObject:firstLetter]){
                    [firstLetterArray addObject:firstLetter];
                }
            }else{
                NSString *firstLetter = rmodel.patientName.mj_firstLetter;
                if(![firstLetterArray containsObject:firstLetter]){
                    [firstLetterArray addObject:firstLetter];
                }
            }
            
        }
         //字母排序
        NSArray *newArray = [firstLetterArray sortedArrayUsingSelector:@selector(compare:)];
        self.firstLetterArray = [NSMutableArray array];
        //
        MJCommonModel *model = [[MJCommonModel alloc]init];
        model.title = MJUILocalizedString(@"All");
        model.isSelect = true;
        [self.firstLetterArray addObject:model];
        //
        for (NSString *item in newArray) {
            MJCommonModel *model = [[MJCommonModel alloc]init];
            model.title = item;
            [self.firstLetterArray addObject:model];
        }
        //一句代码 深拷贝
        NSArray <PatientModel *>*deepCopyAry = [NSMutableArray yy_modelArrayWithClass:[PatientModel class] json:[self.dataArray yy_modelToJSONData]];
        self.tempDataArray = [NSMutableArray arrayWithArray:deepCopyAry];
    }
    
    //
    self.letterView.firstLetterArray = self.firstLetterArray;
    CGFloat letterBgViewH = 0;
    if(self.firstLetterArray.count > 0){
        NSInteger row = 0;
        if(self.firstLetterArray.count < 10){
            row = 1;
        }else if(self.firstLetterArray.count >= 10 && self.firstLetterArray.count < 20){
            row = 2;
        }else{
            row = 3;
        }
        letterBgViewH = 35*row+(row - 1)*6 + 15;
    }else{
        letterBgViewH = 0;
    }
    self.letterBgViewH.constant = letterBgViewH;

}

- (void)showEmptyView{
    if(self.dataArray.count > 0){
        [self hideEmptyView:self.tableView];
        self.tableView.mj_footer.hidden = false;
    }else{
        self.tableView.mj_footer.hidden = true;
        [self showEmptyView:self.tableView emptyStyle:EmptyViewSelectMember];
    }
}

#pragma mark - ArchivesSectionViewDelegate 代理方法
- (void)collectionViewdidSelectItemAtIndex:(NSInteger)index{
    if(index == 0){
        //一句代码 深拷贝
        NSArray <PatientModel *>*deepCopyAry = [NSMutableArray yy_modelArrayWithClass:[PatientModel class] json:[self.dataArray yy_modelToJSONData]];
        self.tempDataArray = [NSMutableArray arrayWithArray:deepCopyAry];
    }else{
        self.tempDataArray = [NSMutableArray array];
        MJCommonModel *model = self.firstLetterArray[index];
        for (PatientModel *itemModel in self.dataArray) {
            
            if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleRU){
                if([itemModel.patientName.mj_firstRuLetter isEqualToString:model.title]){
                    [self.tempDataArray addObject:itemModel];
                }
            }else{
                if([itemModel.patientName.mj_firstLetter isEqualToString:model.title]){
                    [self.tempDataArray addObject:itemModel];
                }
            }
            
            
        }
    }
    [self.tableView reloadData];
}

#pragma mark - TableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.tempDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SelectMemberTbvCell *cell = [SelectMemberTbvCell reuseForTableView:tableView forIndexPath:indexPath];
    PatientModel *patientModel = self.tempDataArray[indexPath.row];
    cell.model = patientModel;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.tempDataArray enumerateObjectsUsingBlock:^(PatientModel *obj, NSUInteger idx, BOOL *stop) {
        obj.isSelect = false;
    }];
    PatientModel *patientModel = self.tempDataArray[indexPath.row];
    patientModel.isSelect = true;
    [self.tableView reloadData];

    MJWeakSelf
    MJUIAfter_GCD(0.3, ^{
        [weakSelf.baseAlertView dismissCompletion:^{
            if(weakSelf.confirmBlock){
                weakSelf.confirmBlock(patientModel);
            }
        }];
    });
}

#pragma mark - 懒加载
- (NSMutableArray *)dataArray {
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

@end
